<template>
    <n-grid :x-gap="15" :cols="14" style="height: 100%;">
        <n-grid-item :span="3">
            <div style="background-color: #ffffff; height: 100%;">
                <div style="display: flex; flex-direction: row; align-items: center; margin-left: 20px; padding-top: 10px;">
                    <label style="font-size: 20px; font-weight: bold;">角色</label>
                    <n-icon ml-15 cursor-pointer size="17" @click="refresh">
                        <icon-ant-design:reload-outlined/>
                    </n-icon>
                    <n-icon color-primary ml-65 cursor-pointer size="17" @click="showAddRoleForm = true">
                        <icon-ant-design:plus-outlined/>
                    </n-icon>
                </div>
                <n-divider style="margin-top: 10px; margin-bottom: 15px;"/>
                <n-input placeholder="搜索角色" style="width: 90%;" ml-10/>
                <n-list hoverable clickable :show-divider="false" style="width: 90%; padding-top: 5px;" ml-10>
                    <n-list-item v-for="role in roles" :key="role.id"
                                 style="font-size: 13px; height: 35px;"
                                 :class="role.authority === searchCondition.role ? 'n-list-item-selected' : 'n-list-item-not-selected'"
                                 @click="chooseRole(role)">
                        <div style="display: flex; flex-direction: row; align-items: center;">
                            {{ role.name }} <!-- 显示 role.name -->
                            <n-tag v-if="role.authority === 'SUPERADMIN'" :bordered="false" type="warning" size="small" ml-5>
                                最高权限
                            </n-tag>
                        </div>
                    </n-list-item>
                </n-list>
            </div>
        </n-grid-item>
        <n-grid-item :span="11" mr-20>
            <n-tabs
                default-value="role-user"
                type="card"
                placement="top"
                animated
                size="small"
                style="margin-top: 10px;"
                trigger="click"
            >
                <n-tab-pane name="role-user" tab="角色用户" style="height: 72vh;">
                    <n-form ref="form"
                            :model="searchCondition"
                            label-placement="left"
                            label-align="right"
                            label-width="80px"
                            style="margin-top: 10px;"
                            :show-require-mark="false">
                        <div class="grid md:flex md:flex-wrap md:gap-x-1">
                            <n-form-item>
                                <n-input round placeholder="输入真实姓名" v-model:value="searchCondition.name" ml-10 clearable>
                                    <template #suffix>
                                        <n-icon cursor-pointer size="17" @click="searchByCondition">
                                            <icon-ph:magnifying-glass-bold />
                                        </n-icon>
                                    </template>
                                </n-input>
                            </n-form-item>
                            <n-form-item>
                                <n-button style="border-radius: 5px; margin-left: 15px;" type="primary" @click="showTransferAdmin = true">添加用户</n-button>
                            </n-form-item>
                        </div>
                    </n-form>
                    <n-data-table
                        style="padding-left: 10px; padding-right: 10px;"
                        remote
                        :single-line="false"
                        ref="table"
                        :columns="columns"
                        :data="roleList"
                        :loading="loading"
                        :pagination="paginationReactive"
                        :row-key="rowKey"
                        :max-height="250"
                        @update:checked-row-keys="handleCheck"
                        bordered
                    />
                    <n-modal v-model:show="showTransferRole" title="迁移角色" preset="dialog" @close="onClose"
                             style="height: 200px;width: 400px">
                                    <n-select v-model:value="transferRole"
                                              :options="transferRoleList"
                                              placeholder="选择角色"
                                              style="width: 330px; margin-top: 30px;"
                                              size="large"
                                              filterable/>
                        <div class="submit-row">
                            <n-button type="primary" @click="handleTransferRole">提交</n-button>
                        </div>
                    </n-modal>
                    <n-modal v-model:show="showTransferAdmin" title="游客分配角色" preset="dialog" @close="onClose"
                             style="height: 200px;width: 400px">
                        <n-select v-model:value="transferAdmin"
                                  :options="transferAdminList"
                                  placeholder="选择游客"
                                  style="width: 330px; margin-top: 30px;"
                                  size="large"
                                  filterable/>
                        <div class="submit-row">
                            <n-button type="primary" @click="handleTransferAdmin">提交</n-button>
                        </div>
                    </n-modal>
                    <n-modal v-model:show="showAddRoleForm" title="添加角色" preset="dialog" @close="onClose"
                             style="height: 300px;width: 400px">
                        <n-form-item label="角色名称：" path="name" mt-20>
                            <n-input v-model:value="roleInfo.name" placeholder="请输入角色名称" />
                        </n-form-item>
                        <n-form-item label="管理权限：" path="authority">
                            <n-input v-model:value="roleInfo.authority" placeholder="请输入管理权限" />
                        </n-form-item>
                        <div class="submit-row">
                            <n-button type="primary" @click="addRole">提交</n-button>
                        </div>
                    </n-modal>
                </n-tab-pane>
                <n-tab-pane name="role-authority" tab="功能权限">
                </n-tab-pane>
            </n-tabs>
        </n-grid-item>
    </n-grid>
</template>
<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {NButton} from 'naive-ui'
import AccountActions from "@/views/admin/system/account-manage/components/account-actions.vue";
const showAddRoleForm = ref(false);
const roleInfo = ref({
    name: "",
    authority: ""
})
const showForm = ref(false);
const roles = ref([])
const transferRole = ref("游客")
const transferAdmin = ref(null)
let transferRoleEntity = null
const showTransferRole = ref(false)
const showTransferAdmin = ref(false)
const refresh = () => {
    searchCondition.value = {
        name: "",
        role: "SUPERADMIN"
    }
    searchByCondition()
}
const onClose = () => {
    transferRole.value = "游客";
    showTransferRole.value = false;
    showTransferAdmin.value = false;
    showAddRoleForm.value = false;
    roleInfo.value.name = ""
    roleInfo.value.authority = "";
}
const handleTransferRole = async () => {
    try {
        transferRoleEntity.role = transferRole.value
        const res = await api.updateAdmin({
            ...transferRoleEntity
        })
        if(res.code === 200) {
            onClose()
            $message.success("更新角色成功！")
            await searchByCondition()
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("更新角色失败！")
    }finally{
        loading.value = false
    }
}
const handleTransferAdmin = async () => {
    try {
        const res = await api.updateAdmin({
            id: transferAdmin.value,
            role: searchCondition.value.role
        })
        if(res.code === 200) {
            onClose()
            $message.success("分配用户角色成功！")
            await searchByCondition()
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("更新角色失败！")
    }finally{
        loading.value = false
    }
}
const chooseRole = (role) => {
    searchCondition.value.name = "";
    searchCondition.value.role = role.authority;
    searchByCondition()
}
const handleClose = () => {
    showForm.value = false;
};
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const roleList = ref([])
const range = ref(null)
const value = ref("全部")
const checkedRowKeysRef = ref([]);
const transferRoleList = ref([
])
const transferAdminList = ref([
])
const searchCondition = ref({
    name: "",
    role: "SUPERADMIN"
});
const admins = ref([])
admins.value.push({
    label:'全部',
    value:-1,
})
const columns = [
    {
        type: 'selection'
    },
    {
        key: 'username',
        title: '用户名',
        width: 70,
    },

    {
        key: 'name',
        title: '真实姓名',
        width: 50,

    },
    {
        key: 'phone',
        title: '手机号',
        width: 90,
    },
    {
        key: 'operation',
        title: '操作',
        width: 40,
        render(row) {
            return h(
                AccountActions,
                {
                    onClickEdit: () => onEditProductCategory(row),
                }
            );
        }
    },
]
let total = 0
const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [5, 10, 20],
    itemCount:0,
    prefix: () => {
        return '查询出 ' + total + '条记录';
    },
    onChange: (page) => {
        paginationReactive.page = page;
        queryByPage()
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize;
        paginationReactive.page = 1;
        queryByPage()
    }
});
const handleCheck = (rowKeys) => {
    checkedRowKeysRef.value = rowKeys;
}
const deleteSelectProduct = () => {
    if(checkedRowKeysRef.value.length <= 0) {
        $message.error("当前并未选择管理员！")
        return
    }
    $dialog.confirm({
        title: '警告',
        content: '您确定删除当前所选管理员？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            const ids = checkedRowKeysRef.value.join(",")
            loading.value = true
            try {
                const res = await api.deleteProductCategories({params:{ids}})
                if(res.code === 200) {
                    $message.success("删除所选管理员成功！")
                    await searchByCondition()
                }
                else {
                    $message.error(res.message)
                }
            } catch (err) {
                $message.error("删除所选管理员失败！")
            }finally{
                loading.value = false
            }
        },
    })
}
const searchByCondition = async () => {
    loading.value = true
    try {
        paginationReactive.page = 1;
        const res = await api.findPageAdmin({
            params: {
                ...searchCondition.value,
                pageNum: paginationReactive.page,
                pageSize: paginationReactive.pageSize,
            }
        })
        if(res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
            const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
            roleList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: baseCount + i + 1,
                }
            })
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("查询管理员失败！")
    }finally{
        loading.value = false
    }
}
const exportListInfo = async () => {
    const res = await api.exportProductCategoryList({
        adminId: searchCondition.value.adminId
    })
    const contentDisposition = res.headers["content-disposition"]
    // console.log(res)
    let original_fileName = ""
    if(contentDisposition) {
        const uri = res.headers["content-disposition"].split("=")[1]
        original_fileName = window.decodeURI(uri)
    }
    const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
    if(window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, original_fileName);
    } else{
        const fileName = original_fileName;
        const elink = document.createElement('a')
        document.body.appendChild(elink)
        elink.download= fileName;
        elink.style.display ="none"
        elink.href  = window.URL.createObjectURL(blob)
        elink.click()
        window.URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
    }
}
const onDeleteProductCategory = async (role) => {
    $dialog.confirm({
        title: '警告',
        content: '您确定删除当前管理员？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            const {id} = role
            loading.value = true
            try {
                const res = await api.deleteProductCategory({id})
                if(res.code === 200) {
                    $message.success("删除管理员成功！")
                    await queryByPage()
                }
                else {
                    $message.error(res.message)
                }
            } catch (err) {
                $message.error("删除管理员失败！")
            }finally{
                loading.value = false
            }
        }
    })
}
const onEditProductCategory = async (role) => {
    showTransferRole.value = true
    transferRoleEntity = role
}
const queryByPage = async () => {
    loading.value = true
    try {
        const res = await api.findPageAdmin(
            {
                params:{
                    role: searchCondition.value.role,
                    pageNum:paginationReactive.page,
                    pageSize:paginationReactive.pageSize,
                }
            })
        if(res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
            const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
            roleList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: baseCount + i + 1,
                }
            })
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取管理员失败！")
    }finally{
        loading.value = false
    }
}
const queryRoleList = async () => {
    loading.value = true
    try {
        const res = await api.findAllRole()
        if(res.code === 200) {
            roles.value = res.data
            res.data.map((role)=>{
                transferRoleList.value.push({
                    label: role.name,
                    value: role.authority
                })
            })
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取角色信息失败！")
    }finally{
        loading.value = false
    }
}
const queryAdminList = async () => {
    loading.value = true
    try {
        const res = await api.findAdminByRole({
            role: "User"
        })
        if(res.code === 200) {
            res.data.map((role)=>{
                transferAdminList.value.push({
                    label: role.name,
                    value: role.id
                })
            })
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取游客信息失败！")
    }finally{
        loading.value = false
    }
}
const addRole = async () => {
    loading.value = true
    try {
        const res = await api.addRole({
            ...roleInfo.value
        })
        if(res.code === 200) {
            await queryRoleList()
            onClose()
            $message.success("添加角色成功！")
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("添加角色失败！")
    }finally{
        loading.value = false
    }
}
const rowKey = (rowData) => {
    return rowData.id
}
onMounted(()=>{
    queryRoleList()
    queryByPage()
    queryAdminList()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
    text-align: center;

}
:deep(.n-select) {
    width: 120px !important;
}

:deep(.two-line-description) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 控制显示的行数 */
    overflow: hidden;
}
:deep(.n-tabs-tab) {
    background-color: #ffffff88 !important;
}
:deep(.n-tabs-tab--active) {
    font-weight: bold !important;
    background-color: #ffffff !important;
}
:deep(.n-tabs-pane-wrapper) {
    background-color: #ffffff !important;
    margin-top: -2px !important;
}
:deep(.n-data-table-th__title) {
    font-weight: bold !important;
    font-size: 13px !important;
}
:deep(.n-list-item-not-selected:hover) {
    background-color: #005BF50A !important;
}
:deep(.n-list-item-selected) {
    background-color: #005BF519 !important;
    color: #005bf5;
}
:deep(.n-list-item-selected:hover) {
    background-color: #005BF519 !important;
    color: #005bf5;
}
.submit-row {
    justify-content: center;
    display: flex;
    width: 100%;
    margin-top: 20px;
}
</style>
